#ifndef SQLITETHREADSTORAGE_H
#define SQLITETHREADSTORAGE_H

#include <stdint.h>
#include "threadstorage.h"

namespace Wishmaster {

class SQLiteThreadStorage : public ThreadStorage
{
	Q_OBJECT
public:
	SQLiteThreadStorage(const QString& root);
	virtual ~SQLiteThreadStorage();

	bool storeThread(const QString& host, const QString& board, Thread* thread);
	ThreadPtr restoreThread(Board* board, unsigned long thread_id, bool restorePosts = true);
	bool restoreThread(Board* board, unsigned long thread_id, Thread* thread);

	void deleteThread(unsigned long id);
	void setMaxThreads(int max);

	unsigned long thread(const QString& host, const QString& board, unsigned long thread_id);

	unsigned long setThread(const ThreadEntry& entry);
	ThreadEntry getThread(unsigned long thread_entry_id);
	QString threadStorageDir(const QString& host, const QString& board, unsigned long thread_id);
	QString threadStorageDir(const PostId& postId);

	QList<unsigned long> threadList(const QString& host, const QString& board);
	QList<unsigned long> threadList(const QString& host, const QString& board, uint32_t flags);

	QList<unsigned long> deleteOldThreads(const QString& host, const QString& board);

	static const uint32_t ThreadHidden = (1 << 0);
	static const uint32_t ThreadDead = (1 << 1);
	static const uint32_t ThreadInvalid = (1 << 31);
	static const uint32_t ThreadArchived = (1 << 2);
	static const uint32_t ThreadResponded = (1 << 3);

	static const uint32_t PostHidden = (1 << 0);
	static const uint32_t PostThumbLocal = (1 << 1);
	static const uint32_t PostPicLocal = (1 << 2);

	static const unsigned long InvalidThreadId = 0xffffffff;

protected:
	bool postExists(const QString& host, const QString& board, unsigned long thread_id, unsigned long post_id);
	void clearThread(unsigned long thread_entry_id);
	QString thumb(const QString& host, const QString& board, unsigned long thread_id, unsigned long post_id);
	QString threadName(unsigned long thread_entry_id);
	bool addPost(unsigned long thread_entry_id, PostPtr post, uint32_t flags);
	QList<unsigned long> deleteThreadsBySql(const QString& sql);
	uint32_t makeFlags(Thread* thr);
	void setFlags(ThreadPtr thr, uint32_t flags);
	void setFlags(Thread* thr, uint32_t flags);
	void restorePosts(Board* b, Thread* thr, unsigned long thread_entry_id);
	bool storePosts(Board* b, Thread* thr, unsigned long thread_entry_id);
	QString makeThumbFilename(unsigned long post_id, int attachIndex, QString format) const;
	QString makePicFilename(unsigned long post_id, QString format) const;
	QString saveAttachments(PostPtr& post);
	void restoreAttachments(PostPtr& post, const QString& attachments);

	void convertFrom060Format();

private:
	QString m_root;
	CppSQLite3DB m_sqlite;
	int m_maxThreads;
};

} // namespace Wishmaster

#endif // SQLITETHREADSTORAGE_H
